package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SysRoleController.class);
    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public String list(Model model) {
        List<SysRole> list = sysRoleService.findAll();
        model.addAttribute("list", list);
        return "role/list";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        return "role/save";
    }

    @PostMapping("/save")
    public String save(SysRole sysRole) {
        try {
        SysUser loginUser = session(Constants.SESSION_USER);
        boolean ok = false;
        if (sysRole.getId() == null) {
            // 如果是添加用户，关联创建用户为当前登陆用户
            sysRole.setCreatedUserId(loginUser.getId());
            sysRole.setCreatedTime(new Date());
            ok = sysRoleService.insert(sysRole);
        } else {
            // 如果是修改用户，关联修改用户为当前登陆用户
            sysRole.setUpdatedUserId(loginUser.getId());
            sysRole.setUpdatedTime(new Date());
            ok = sysRoleService.update(sysRole);
        }
        if (ok) {
            // 保存成功，跳回列表页面
            return redirect("/main/role/list");
        }
    } catch (Exception e) {
        LOGGER.error("SysUserController中的doSave方法执行发生错误。", e);
        throw new RuntimeException(e);
    }
        return "role/save";
    }

    @ResponseBody
    @GetMapping("/codeExist")
    public Object supCodeExist(@RequestParam("code") String code){
        Map<String,Object> map = new HashMap<>();
        try{
            // 角色编号不可为空
            if(StringUtils.isEmpty(code)){
                map.put("exist", 1);
            }else {
                SysRole sysRole = sysRoleService.getCode(code);
                if(null != sysRole) {
                    map.put("exist", 1);
                }else {
                    map.put("exist", 0);
                }
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }

    @ResponseBody
    @GetMapping("/{id}/view")
    public String ajaxView(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            SysRole sysRole=sysRoleService.getById(id);
            if (sysRole != null) {
                map.put("code", 200);
                map.put("data", sysRole);
            } else {
                map.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysRoleController中的ajaxView方法执行发生错误。 ", e);
            map.put("code", 500);
        }
        return JSON.toJSONString(map);
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {

        SysRole sysRole = null;
        try {
            sysRole = sysRoleService.getById(id);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("sysRole", sysRole);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Integer id, Model model) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean num = sysRoleService.delete(id);
            if (num) {
                map.put("code", 200);
                map.put("msg", "删除成功");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return map;
    }
}
